<template>
  <div class="content mar_10">
    <div class="h_l_img">
      <div class="img"><img src="@/assets/images/l_img.jpg" width="188" height="188" /></div>
      <div class="pri_bg">
        <span class="price fl">￥53.00</span>
        <span class="fr">16R</span>
      </div>
    </div>
    <div class="hot_pro">
      <div id="featureContainer">
        <div id="feature">
          <div id="block">
            <!-- 使用Element Plus Carousel组件 -->
            <el-carousel 
              :interval="5000" 
              arrow="always"
              indicator-position="none"
              height="228px"
              ref="carouselRef"
            >
              <!-- 每页显示4个商品 -->
              <el-carousel-item v-for="(page, pageIndex) in paginatedProducts" :key="pageIndex">
                <ul class="featureUL">
                  <li class="featureBox" v-for="product in page" :key="product.id">
                    <div class="box">
                      <div class="h_icon" v-if="product.isHot"><img src="@/assets/images/hot.png" width="50" height="50" /></div>
                      <div class="imgbg">
                        <a href="#" @click.prevent="viewProduct(product.id)">
                          <img :src="getProductImage(product)" width="160" height="136" :alt="product.name" @error="handleImageError" />
                        </a>
                      </div>
                      <div class="name">
                        <a href="#" @click.prevent="viewProduct(product.id)">
                          <!-- 移除brand字段，因为后端数据没有提供 -->
                          {{ product.name }}
                        </a>
                      </div>
                      <div class="price">
                        <span style="color: #ff4e00;">￥<span>{{ product.price }}</span></span> &nbsp; {{ product.points || 0 }}R
                      </div>
                    </div>
                  </li>
                </ul>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { queryProduct } from '@/api/productApi'

export default {
  name: 'HotProducts',
  props: {
    products: {
      type: Array,
      default: () => []
    }
  },
  setup(props, { emit }) {
    const randomProducts = ref([])
    const carouselRef = ref(null)
    
    // 分页商品数据，每页4个商品
    const paginatedProducts = computed(() => {
      const products = props.products.length > 0 ? props.products : randomProducts.value
      const pages = []
      for (let i = 0; i < products.length; i += 4) {
        pages.push(products.slice(i, i + 4))
      }
      return pages
    })
    
    // 显示的商品数据
    const displayProducts = computed(() => {
      return props.products.length > 0 ? props.products : randomProducts.value
    })
    
    const loadRandomProducts = async () => {
      try {
        // 获取20个随机商品，确保有足够的商品用于轮播
        const res = await queryProduct({ pageSize: 20 })
        let products = []
        
        if (res && res.data) {
          products = Array.isArray(res.data) ? res.data : []
        } else if (Array.isArray(res)) {
          products = res
        }
        
        // 如果商品数量不足8个，全部使用
        // 如果商品数量超过8个，随机选择8个
        if (products.length <= 8) {
          randomProducts.value = products
        } else {
          // 随机选择8个商品
          const shuffled = [...products].sort(() => 0.5 - Math.random())
          randomProducts.value = shuffled.slice(0, 8)
        }
      } catch (error) {
        console.error('获取随机商品失败:', error)
        // 如果获取失败，使用空数组
        randomProducts.value = []
      }
    }
    
    const viewProduct = (id) => {
      emit('view-product', id)
    }
    
    // 获取商品图片
    const getProductImage = (product) => {
      if (product.fileName) {
        try {
          // 尝试返回实际图片路径
          return require(`@/assets/files/${product.fileName}`)
        } catch (error) {
          // 如果图片不存在，返回默认图片
          console.warn(`商品图片加载失败: ${product.fileName}`, error)
          return require('@/assets/images/default_product.jpg')
        }
      }
      // 如果没有fileName字段，返回默认图片
      return require('@/assets/images/default_product.jpg')
    }
    
    // 处理图片加载错误
    const handleImageError = (event) => {
      console.log('图片加载错误，尝试使用默认图片')
      try {
        event.target.src = require('@/assets/images/default_product.jpg')
      } catch (error) {
        console.error('默认图片加载失败:', error)
        // 如果默认图片也加载失败，设置为空白图片
        event.target.src = ''
      }
    }
    
    // 监听商品数据变化
    watch(displayProducts, () => {
      // Element Plus Carousel会自动处理数据变化
    })
    
    onMounted(async () => {
      // 如果没有传入products，则获取随机商品
      if (props.products.length === 0) {
        await loadRandomProducts()
      }
    })
    
    return {
      randomProducts,
      carouselRef,
      paginatedProducts,
      displayProducts,
      loadRandomProducts,
      viewProduct,
      getProductImage,
      handleImageError
    }
  }
}
</script>

<style scoped>

</style>